package com.eras.shoes

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Paint
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.appcompat.widget.ListPopupWindow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.eras.shoes.contents.Api
import com.eras.shoes.contents.BleBean
import com.eras.shoes.contents.DictData
import com.eras.shoes.contents.DictItem
import com.eras.shoes.contents.Global
import com.eras.shoes.contents.MessageEvent
import com.eras.shoes.contents.SizeConfig
import com.eras.shoes.contents.UserConfigBean
import com.eras.shoes.contents.UserInfo
import com.eras.shoes.databinding.ActivityMainBinding
import com.eras.shoes.db.MacBlacklistManager
import com.eras.shoes.ui.AssemblyActivity
import com.eras.shoes.ui.BindActivity
import com.eras.shoes.ui.CalibrateActivity
import com.eras.shoes.ui.InsoleOneActivity
import com.eras.shoes.ui.InsoleTwoActivity
import com.eras.shoes.ui.LoginActivity
import com.eras.shoes.ui.MainBoardActivity
import com.eras.shoes.ui.UserInfoDetail
import com.eras.shoes.ui.theme.ERASLineOfProductionTheme
import com.eras.shoes.utils.BluetoothController
import com.eras.shoes.utils.DimensUtil
import com.eras.shoes.utils.OkHttpUtils
import com.eras.shoes.utils.OkHttpUtils.DataCallBack
import com.eras.shoes.utils.ToastUtils
import com.eras.shoes.view.RxDialogWriteSureCancel
import com.eras.shoes.view.popupdialog.PopupSheet
import com.eras.shoes.view.popupdialog.PopupSheetCallback
import com.eras.shoes.view.popupdialog.RxDialogcalibrateSureCancel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.Request
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.text.MessageFormat
import java.util.*


class MainActivity : ComponentActivity(), View.OnClickListener {

    private val PERMISSIONS_REQUEST_CODE = 101
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.BLUETOOTH,
        Manifest.permission.BLUETOOTH_ADMIN,
        Manifest.permission.ACCESS_FINE_LOCATION
    )
    private lateinit var roles: List<String> //角色
    lateinit var dictLists: List<DictItem>
    private val sharedPref by lazy {
        getSharedPreferences("login_prefs", Context.MODE_PRIVATE)
    }

    private var shoesSizeB: String = ""//鞋子大小
    var shoeSex: Int = -1//鞋性别
    //公司
    var companyCode: String = ""//ZH和XZ
    var companyName: String = ""
    var companyConfig: String = ""
    //训练仪
    var wordCode: String = ""//ZH和XZ
    var wordName: String = ""
    var wordConfig: String = ""
    //特征词
    var shoesCode: String = ""//ZH和XZ
    var shoesName: String = ""
    var shoesConfig: String = ""
//款型
    var serialCode: String = ""
    var serialName: String = ""
    var serialConfig: String = ""
//颜色
    var colorCode: String = ""
    var colorlName: String = ""
    var colorConfig: String = ""
//大小
    var sizeCode: String = ""
    var sizelName: String = ""
    var sizeConfig: String = ""
    //规格代码
    var specificationCode: String = ""
    var specificationName: String = ""
    var specificationConfig: String = ""
    //机动代码
    var mobileCode: String = ""
    var mobileName: String = ""
    var mobileConfig: String = ""

    var footType: String = ""
//    var shoesColor: String = "0"
//    var shoesSizeW: String = "0"
//    var calibShoesTypeCode: String = ""
//    var calibShoesTypeName: String = ""
//    var calibShoesTypeConfig: String = ""
//    var calibShoesSizeCode: String = ""
//    var calibShoesSizeName: String = ""

private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnMainBoard.setOnClickListener(this)
        binding.btnInsoleOne.setOnClickListener(this)
        binding.btnInsoleTwo.setOnClickListener(this)
        binding.btnAssembly.setOnClickListener(this)
        binding.btnMine.setOnClickListener(this)
        binding.btnMainCalibrate.setOnClickListener(this)
        MacBlacklistManager(this@MainActivity).removeBlacklist()

        // 初始化定位管理器
        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
        // 开始定位流程
        startLocationProcess()
        Log.e("MainActivity", "onCreate")
    }

    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this)) { //加上判断
            EventBus.getDefault().register(this)
        }
        Global.connectState = 0
        checkPermissions()
//        // 检查权限
//        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
//            != PackageManager.PERMISSION_GRANTED
//        ) {
//            requestPermissions(REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE)
//        }
        val savedUsername = sharedPref.getString("username", "")
        binding.tvUserName.text = savedUsername
        getUserDetail()
//        checkLocation()
//        if (checkPermission()) {
//            startNetworkLocation()
//        }
        getDictConfig()
        if (!isLocationReceived && !isLocationRequestActive) {
            startLocationProcess()
        }
        val token = Global.token
        if (token == "") {
            val intent = Intent(this@MainActivity, LoginActivity::class.java)
            startActivity(intent)
            finish()
        }

//        initDate()
    }

    override fun onClick(p0: View?) {
        val toast = ToastUtils()
        when (p0?.id){
            R.id.btn_main_board -> {
                showDialog("1")
            }
            R.id.btn_insole_one -> {
                val intent = Intent(this@MainActivity, InsoleOneActivity::class.java)
                startActivity(intent)
//                toast.show(this, getString(R.string.insole))
            }
            R.id.btn_insole_two -> {
                val intent = Intent(this@MainActivity, InsoleTwoActivity::class.java)
                startActivity(intent)
            }
            R.id.btn_assembly -> {
                val intent = Intent(this@MainActivity, AssemblyActivity::class.java)
                startActivity(intent)
            }
            R.id.btn_mine -> {
                val intent = Intent(this@MainActivity, UserInfoDetail::class.java)
                startActivity(intent)
            }
//            R.id.btn_main_bind -> {
//                val intent = Intent(this@MainActivity, BindActivity::class.java)
//                startActivity(intent)
////                val rxDialogSureCancel: RxDialogBindSureCancel = RxDialogBindSureCancel(this@MainActivity)
////                rxDialogSureCancel.setRadioBindFemaleListener(View.OnClickListener {
////                    rxDialogSureCancel.dialogRadioBindFemale.isChecked = true
////                    rxDialogSureCancel.dialogRadioBindMale.isChecked = false
////                    shoeSex = 1
////                })
////                rxDialogSureCancel.setRadioBindMaleListener(View.OnClickListener {
////                    rxDialogSureCancel.dialogRadioBindMale.isChecked = true
////                    rxDialogSureCancel.dialogRadioBindFemale.isChecked = false
////                    shoeSex = 0
////                })
////                rxDialogSureCancel.setdialogTvBindShoesSizeListener(View.OnClickListener {
////                    val arrayShoesSize: Array<String> = resources.getStringArray(R.array.shoe_size_list)
////                    selectShoesSize(rxDialogSureCancel.dialogTvBindShoesSize, arrayShoesSize)
////                })
////                rxDialogSureCancel.setCancelListener(View.OnClickListener {
////                    rxDialogSureCancel.cancel()
////                })
////                rxDialogSureCancel.setSureListener(View.OnClickListener {
////                    if (shoeSex == -1) {
////                        ToastUtils().show(this@MainActivity, "请选择鞋子款式")
////                        return@OnClickListener
////                    }
////                    if (shoesSizeB.equals("")) {
////                        ToastUtils().show(this@MainActivity, "请选择鞋子大小")
////                        return@OnClickListener
////                    }
////                    rxDialogSureCancel.dismiss()
////                    intentNewActivity(shoeSex, shoesSizeB)
////
////                })
////                rxDialogSureCancel.show()
//
//            }
            R.id.btn_main_calibrate -> {
                showDialog("0")
//                val rxDialogCali: RxDialogcalibrateSureCancel =
//                    RxDialogcalibrateSureCancel(this@MainActivity)
//                setCalibDialogDate(rxDialogCali)
//                if (Global.shoesName.equals("") || Global.sizelName.equals("")
//                ) {
//                    rxDialogCali.tvCalibCancel.text = "完善"
//                }
//                rxDialogCali.setDialogLlShoesTypeListener(View.OnClickListener {
//                    dictLists = getItems("FEATURE_WORDS")
//                    selectCalibDate(rxDialogCali, rxDialogCali.dialogTvShoesTypeValue, dictLists, 2)
//                })
//                rxDialogCali.setDialogLlShoesSizeListener(View.OnClickListener {
//                    if (rxDialogCali.dialogTvShoesTypeValue.text.equals("")) {
//                        ToastUtils().show(this@MainActivity, "请先选择产品类型")
//                        return@OnClickListener
//                    }
//                    val toJsonObj = JSONObject(shoesConfig)
//                    val sizeArrays: JSONArray = toJsonObj.getJSONArray("size")
//                    Log.e("MainActivity", "shoesConfig="+sizeArrays)
//                    val sizes = sizeList(sizeArrays.toString())
//                    selectCalibSizeDate(rxDialogCali, rxDialogCali.dialogTvShoesSizeValue, sizes, 5)
//                })
//                rxDialogCali.setTvCalibSureListener(View.OnClickListener {
//                    if (rxDialogCali.dialogTvShoesTypeValue.text.equals("")) {
//                        ToastUtils().show(this@MainActivity, "请选择产品")
//                        return@OnClickListener
//                    }
//                    if (rxDialogCali.dialogTvShoesSizeValue.text.equals("")) {
//                        ToastUtils().show(this@MainActivity, "请选择尺码")
//                        return@OnClickListener
//                    }
//                    setUserConfig(companyCode,shoesCode,wordCode,serialCode,specificationCode,Global.footCode,colorCode,sizeCode,colorConfig)
////                    getCalibConfig(rxDialogCali, shoesCode, sizeCode)
//
//                })
//                rxDialogCali.setTvCalibCancelListener(View.OnClickListener {
//                    if (rxDialogCali.tvCalibCancel.text.equals("修改") || rxDialogCali.tvCalibCancel.text.equals("完善")) {
//                        showCailbDownIc(rxDialogCali)
//                        rxDialogCali.tvCalibCancel.text = "取消"
//                    } else if (rxDialogCali.tvCalibCancel.text.equals("取消")) {
//                        dissCalibDownIc(rxDialogCali)
//                        rxDialogCali.tvCalibCancel.text = "修改"
////                        rxDialogSureCancel.dismiss()
//                    }
////                    rxDialogCali.cancel()
//                })
//                dissCalibDownIc(rxDialogCali)
//                rxDialogCali.show()

//                val intent = Intent(this@MainActivity, CalibrateActivity::class.java)
//                startActivity(intent)
            }

        }
    }
    private fun intentCalibActivity(rxDialogSureCancel: RxDialogWriteSureCancel) {
        getCalibConfig(rxDialogSureCancel, shoesCode, sizeCode)
        setUserConfig(companyCode,shoesCode,wordCode,serialCode,specificationCode,Global.footCode,colorCode,sizeCode,colorConfig)

    }
    private fun goIntentCalib() {
        val intent = Intent(this@MainActivity, CalibrateActivity::class.java).apply {
            // 基本数据类型
            putExtra("companyCode", companyCode)
            putExtra("companyName", companyName)
            putExtra("companyConfig", companyConfig)

            putExtra("wordCode", wordCode)
            putExtra("wordName", wordName)
            putExtra("wordConfig", wordConfig)

            putExtra("shoesCode", shoesCode)
            putExtra("shoesName", shoesName)
            putExtra("shoesConfig", shoesConfig)

            putExtra("serialCode", serialCode)
            putExtra("serialName", serialName)
            putExtra("serialConfig", serialConfig)

            putExtra("colorCode", colorCode)
            putExtra("colorlName", colorlName)
            putExtra("colorConfig", colorConfig)

            putExtra("sizeCode", sizeCode)
            putExtra("sizelName", sizelName)
            putExtra("sizeConfig", sizeConfig)

            putExtra("specificationCode", specificationCode)
            putExtra("specificationName", specificationName)
            putExtra("specificationConfig", specificationConfig)

            putExtra("footType", getItems("FOOT_TYPE").toString())
        }
        startActivity(intent)
    }
    private fun intentWriteActivity() {
        val intent = Intent(this@MainActivity, MainBoardActivity::class.java).apply {
            // 基本数据类型
            putExtra("companyCode", companyCode)
            putExtra("companyName", companyName)
            putExtra("companyConfig", companyConfig)

            putExtra("wordCode", wordCode)
            putExtra("wordName", wordName)
            putExtra("wordConfig", wordConfig)

            putExtra("shoesCode", shoesCode)
            putExtra("shoesName", shoesName)
            putExtra("shoesConfig", shoesConfig)

            putExtra("serialCode", serialCode)
            putExtra("serialName", serialName)
            putExtra("serialConfig", serialConfig)

            putExtra("colorCode", colorCode)
            putExtra("colorlName", colorlName)
            putExtra("colorConfig", colorConfig)

            putExtra("sizeCode", sizeCode)
            putExtra("sizelName", sizelName)
            putExtra("sizeConfig", sizeConfig)

            putExtra("specificationCode", specificationCode)
            putExtra("specificationName", specificationName)
            putExtra("specificationConfig", specificationConfig)

            putExtra("footType", getItems("FOOT_TYPE").toString())
        }
        startActivity(intent)
        setUserConfig(companyCode,shoesCode,wordCode,serialCode,specificationCode,Global.footCode,colorCode,sizeCode,colorConfig)

    }

    private fun intentNewActivity(Sex: Int, Size: String) {
        val intent = Intent(this@MainActivity, BindActivity::class.java).apply {
            // 基本数据类型
            putExtra("SHOES_SEX_KEY", Sex)
            putExtra("SHOES_SIZE_KEY", Size)
        }
        startActivity(intent)
    }

    private fun selectSizeDate(rxDialogSureCancel: RxDialogWriteSureCancel, view: TextView, arrays: List<SizeConfig>, tag: Int) {
        // 测量文本最大宽度
        var maxWidth = 0f
        var item: String = ""
        // 测量文本最大宽度
        val paint = Paint()
        for (i in 0 until arrays.size) {
            item = arrays.get(i).name
            val width = paint.measureText(item)
            if (width > maxWidth) {
                maxWidth = width
            }
        }
        val popupSheet: PopupSheet
        val showArrayList = arrays//Arrays.asList(/* ...a = */ *arrays)
        popupSheet =
            PopupSheet(this@MainActivity, view, showArrayList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@MainActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", showArrayList[position].name)
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    view.text = showArrayList[position].name
                    setSerValue(rxDialogSureCancel, tag, showArrayList[position].code, showArrayList[position].name, "")
//                    ToastUtils().show(this@MainBoardActivity, "你选择了"+showArrayList[position])
//                    tvShoesSize.text = MessageFormat.format("{0}", "鞋子尺码：$shoesSize")
                }
            }, DimensUtil.dp2px(this@MainActivity, maxWidth+80F))
        popupSheet.show()
    }

    private fun selectDate(rxDialogSureCancel: RxDialogWriteSureCancel, view: TextView, arrays: List<DictItem>, tag: Int) {
        // 测量文本最大宽度
        var maxWidth = 0f
        var item: String = ""
        // 测量文本最大宽度
        val paint = Paint()
        for (i in 0 until arrays.size) {
            item = arrays.get(i).ruleName
            val width = paint.measureText(item)
            if (width > maxWidth) {
                maxWidth = width
            }
        }


        val popupSheet: PopupSheet
        val showArrayList = arrays//Arrays.asList(/* ...a = */ *arrays)
        popupSheet =
            PopupSheet(this@MainActivity, view, showArrayList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@MainActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", showArrayList[position].ruleName)
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    view.text = showArrayList[position].ruleName
                    if (showArrayList[position].ruleConfig == null) {
                        setSerValue(rxDialogSureCancel, tag, showArrayList[position].ruleCode, showArrayList[position].ruleName, "")
                    } else {
                        setSerValue(
                            rxDialogSureCancel,
                            tag,
                            showArrayList[position].ruleCode,
                            showArrayList[position].ruleName,
                            showArrayList[position].ruleConfig
                        )
                    }
//                    ToastUtils().show(this@MainBoardActivity, "你选择了"+showArrayList[position])
//                    tvShoesSize.text = MessageFormat.format("{0}", "鞋子尺码：$shoesSize")
                }
            }, DimensUtil.dp2px(this@MainActivity, maxWidth+80F))
        popupSheet.show()
    }


    private fun setSerValue(rxDialogSureCancel: RxDialogWriteSureCancel, p0: Int, code: String, name: String, config: String) {
        when (p0) {
            0 -> {
                companyCode = code
                companyName = name
                companyConfig = config
                Global.companyCode = companyCode
                Global.companyName = companyName
                Global.companyConfig = companyConfig
            }
            1 -> {
                wordCode = code
                wordName = name
                wordConfig = config
                Global.wordCode = wordCode
                Global.wordName = wordName
                Global.wordConfig = wordConfig
            }
            2 -> {
                shoesCode = code
                shoesName = name
                shoesConfig = config
                if (!Global.shoesName.equals(shoesName)) {
                    //尺码
                    sizeCode = ""
                    sizelName = ""
                    sizeConfig = ""
                    Global.sizelName = ""
                    Global.sizeCode = ""
                    Global.sizeConfig = ""

                    //款式
                    serialCode = ""
                    serialName = ""
                    serialConfig = ""
                    Global.serialCode = ""
                    Global.serialName = ""
                    Global.serialConfig = ""

                    //型号
                    specificationCode = ""
                    specificationName = ""
                    specificationConfig = ""
                    Global.specificationCode = ""
                    Global.specificationName = ""
                    Global.specificationConfig = ""
                }
                Global.shoesCode = shoesCode
                Global.shoesName = shoesName
                Global.shoesConfig = shoesConfig
            }
            3 -> {
                serialCode = code
                serialName = name
                serialConfig = config
                Global.serialCode = serialCode
                Global.serialName = serialName
                Global.serialConfig = serialConfig
            }
            4 -> {
                colorCode = code
                colorlName = name
                colorConfig = config
                Global.colorCode = colorCode
                Global.colorlName = colorlName
                Global.colorConfig = colorConfig
            }
            5 -> {
                sizeCode = code
                sizelName = name
                sizeConfig = config
                Global.sizeCode = sizeCode
                Global.sizelName = sizelName
                Global.sizeConfig = sizeConfig
            }
            6 -> {
                specificationCode = code
                specificationName = name
                specificationConfig = config
                Global.specificationCode = specificationCode
                Global.specificationName = specificationName
                Global.specificationConfig = specificationConfig
            }
        }
        setDialogDate(rxDialogSureCancel)
    }

    private fun selectShoesSize(tvShoesSize: TextView, arrayShoesSize: Array<String>) {
        // 测量文本最大宽度
        var maxWidth = 0f
        var item: String = ""
        // 测量文本最大宽度
        val paint = Paint()
        for (i in 0 until arrayShoesSize.size) {
            item = arrayShoesSize.get(i)
            val width = paint.measureText(item)
            if (width > maxWidth) {
                maxWidth = width
            }
        }
        val popupSheet: PopupSheet
        val showSizeList = Arrays.asList(*arrayShoesSize)
        popupSheet =
            PopupSheet(this@MainActivity, tvShoesSize, showSizeList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@MainActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", showSizeList[position])
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    shoesSizeB = showSizeList[position].toString()
                    tvShoesSize.text = shoesSizeB
//                    ToastUtils().show(this@BindActivity, "你选择了"+shoesSize+"码")
//                    tvShoesSize.text = MessageFormat.format("{0}", "鞋子尺码：$shoesSize")
                }
            }, DimensUtil.dp2px(this@MainActivity, maxWidth+80F))
        popupSheet.show()
    }

    private fun getUserDetail() {
        OkHttpUtils.getAsyncToken(this@MainActivity, Api.userInfo, true, object : DataCallBack {
            override fun requestFailure(request: Request, e: IOException) {
            }

            @SuppressLint("SetTextI18n")
            @Throws(Exception::class)
            override fun requestSuccess(result: String) {
                val toJsonObj = JSONObject(result)
                Log.e("UserInfoDetail", "返回$toJsonObj")
                val code = toJsonObj.getInt("code")
                if (code == 0) {
                    if (result.contains("data")) {
                        val jsonData = toJsonObj.getString("data")
                        val userInfo = Gson().fromJson(jsonData, UserInfo::class.java)
//                        tvAccount.setText("账号: " + userInfo.account)
//                        tvFactory.setText("工厂: " + userInfo.factory)
//                        tvProductionLine.setText("产线: " + userInfo.productionLine)
//                        tvWorkStation.setText("工位: " + userInfo.workStation)
//                        tvRoleXm.setText("角色: " + userInfo.roles[0])
                        roles = userInfo.roles
                        saveLoginState(userInfo.factory, userInfo.productionLine, userInfo.workStation, userInfo.roles)
                        setRoles(userInfo.roles)
                    }
                } else {
                    val message = toJsonObj["message"] as String
                    ToastUtils().show(this@MainActivity, message)
                }
            }
        })
    }

    private fun setRoles(roles: List<String>) {
        if (roles.contains("ROLE_ADMIN")) {
            binding.btnMainBoard.visibility = View.VISIBLE
            binding.btnMainCalibrate.visibility = View.VISIBLE
        } else if (roles.contains("ROLE_DB")) {
            binding.btnMainBoard.visibility = View.GONE
            binding.btnMainCalibrate.visibility = View.VISIBLE
        } else if (roles.contains("ROLE_XM")) {
            binding.btnMainCalibrate.visibility = View.GONE
            binding.btnMainBoard.visibility = View.VISIBLE
        } else if (roles.contains("ROLE_BIND")) {
            binding.btnMainCalibrate.visibility = View.GONE
            binding.btnMainBoard.visibility = View.GONE
        }
    }

    private fun saveLoginState(factory: String, productionLine: String, workStation: String, roles: List<String>) {
        with(sharedPref.edit()) {
            putString("factory", factory)
            putString("productionLine", productionLine)
            putString("workStation", workStation)
            val builder = StringBuilder()
            val size: Int = roles.size
            for (i in 0 until size) {
                builder.append(roles.get(i))
                if (i < size - 1) {
                    builder.append("、")
                }
            }
            putString("roles", builder.toString())
            apply()
        }
    }

    private fun checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ), 1
            )
        }
    }

    override fun onResume() {
        super.onResume()


    }

    override fun onPause() {
        super.onPause()
        if (isLocationRequestActive) {
            stopLocationUpdates()
        }
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
        stopLocationUpdates()
    }

    override fun onDestroy() {
        super.onDestroy()
        stopLocationUpdates()
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent<*>) {
        when (event.getAction()) {
            MessageEvent.ACTION_GATT_CONNECTED -> {
                var bleBeans: BleBean = event.data as BleBean
                Global.isConnected = true
                Global.connectType = 1
                Global.connectState = 2
//                ToastUtils().show(this@MainActivity, "macAddress:"+bleBeans.address)
                Thread {
                    Thread.sleep(2000) // 暂停2秒
                    BluetoothController.getInstance().closeBuletooth(bleBeans.address) }.start()
            }

            MessageEvent.ACTION_GATT_DISCONNECTED -> {
//                ToastUtils().show(this@MainActivity, "ACTION_GATT_DISCONNECTED")
                BluetoothController.macAddress = null
                Global.isConnected = false
                Global.connectType = -1
                Global.connectState = 0
            }

            MessageEvent.BLE_SCAN_RESULT -> {
                // 添加蓝牙
            }

        }
    }

    private fun checkLocation() {
        // 检查并请求位置权限
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                100
            )
        } else {
            getLocation()
        }
    }
    private fun getLocation() {
        Log.e("MainActivity", "getLocation")
//        LocationUtils.getCurrentLocation(this@MainActivity) { lat, lng ->
//            // 在这里处理获取到的经纬度
//            println("纬度: $lat, 经度: $lng")
//            Global.lat = lat
//            Global.lng = lng
//            Log.e("MainActivity", "纬度: "+lat+", 经度: "+lng)
//        }
    }

//    private lateinit var locationManager: LocationManager
    private val locationPermissionCode = 1001
    private fun checkPermission(): Boolean {
        return if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                locationPermissionCode)
            false
        } else true
    }

    @SuppressLint("MissingPermission")
    private fun startNetworkLocation() {
        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER,
                10000,  // 10秒更新间隔
                10f,    // 10米距离变化阈值
                locationListener
            )
        } else {
            ToastUtils().show(this@MainActivity, "请开启网络定位")
//            Toast.makeText(this, "请开启网络定位", Toast.LENGTH_SHORT).show()
        }
    }


//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if (requestCode == locationPermissionCode && grantResults.isNotEmpty()) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                startNetworkLocation()
//            }
//        }
//    }

    private val locationListener: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            val latitude: Double = location.getLatitude()
            val longitude: Double = location.getLongitude()
            val result = String.format(
                "网络定位结果:\n纬度: %.6f\n经度: %.6f",
                latitude, longitude
            )
            Global.lat = latitude
            Global.lng = longitude
            Log.e("MainActivity", "纬度: " + latitude + ", 经度: " + longitude)
        }
    }

    private fun getDictConfig() {
        OkHttpUtils.getAsyncToken(this@MainActivity, Api.dictConfig, true, object : DataCallBack {
            override fun requestFailure(request: Request, e: IOException) {
            }

            @SuppressLint("SetTextI18n")
            @Throws(Exception::class)
            override fun requestSuccess(result: String) {
                val toJsonObj = JSONObject(result)
                Log.e("getDictConfig", "返回$toJsonObj")
                val code = toJsonObj.getInt("code")
                if (code == 0) {
                    if (result.contains("data")) {
                        getUserConfig()//请求获取用户当前产线配置
                        val jsonData = toJsonObj.getJSONArray("data")
                        Global.dictConfig = jsonData.toString()
                        try {
                            val dictList = parseDictList(jsonData.toString())

                            dictList.forEach { dictData ->
                                println("字典类型: ${dictData.dictName}")

                                dictData.items.forEach { item ->
                                    println("  项: ${item.ruleName} (代码: ${item.ruleCode})")

//                                    item.ruleConfig?.let { configJson ->
//                                        val sizes = sizeList(configJson)
//                                        sizes.forEach { size ->
//                                            println("    尺寸: ${size.name} (代码: ${size.code})")
//                                        }
//                                    }
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                    }
                } else {
                    val message = toJsonObj["message"] as String
                    ToastUtils().show(this@MainActivity, message)
                }
            }
        })
    }

    private fun getItems(code: String): MutableList<DictItem> {
        var dictList = mutableListOf<DictItem>()
        try {
            parseDictList(Global.dictConfig).forEach { dictData ->
                println("字典类型: ${dictData.dictName}")
                if (code.equals(dictData.dictCode)) {
                    val items: MutableList<DictItem> = dictData.items
                    dictList = items
                    return items
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return dictList
    }

    private fun parseDictList(json: String): List<DictData> {
        return Gson().fromJson(json, object : TypeToken<List<DictData>>() {}.type)
    }

//    private fun parseSizeConfig(json: String): List<SizeConfig> {
//        return Gson().fromJson(json, object : TypeToken<List<SizeConfig>>() {}.type)
//    }
private fun sizeList(json: String): List<SizeConfig> {
    return Gson().fromJson(json, object : TypeToken<List<SizeConfig>>() {}.type)
}


    private fun reSetValue() {
        companyCode = ""//ZH和XZ
        companyName = ""
        companyConfig = ""
        //训练仪
        wordCode = ""//ZH和XZ
        wordName = ""
        wordConfig = ""
        //特征词
        shoesCode = ""//ZH和XZ
        shoesName = ""
        shoesConfig = ""
//款型
        serialCode = ""
        serialName = ""
        serialConfig = ""
//颜色
        colorCode = ""
        colorlName = ""
        colorConfig = ""
//大小
        sizeCode = ""
        sizelName = ""
        sizeConfig = ""
        //规格代码
        specificationCode = ""
        specificationName = ""
        specificationConfig = ""
    }

    private fun getUserConfig() {
        OkHttpUtils.getAsyncToken(this@MainActivity, Api.getConfig, true, object : DataCallBack {
            override fun requestFailure(request: Request, e: IOException) {
            }

            @SuppressLint("SetTextI18n")
            @Throws(java.lang.Exception::class)
            override fun requestSuccess(result: String) {
                val toJsonObj = JSONObject(result)
                Log.e("getUserConfig", "返回$toJsonObj")
                val code = toJsonObj.getInt("code")
                if (code == 0) {
                    if (result.contains("data")) {
                        val jsonData = toJsonObj.getString("data")
                        val userInfo = Gson().fromJson(
                            jsonData,
                            UserConfigBean::class.java
                        )
                        UserConfigBean(
                            userInfo.company,
                            userInfo.featureWords,
                            userInfo.coreWords,
                            userInfo.modelCode,
                            userInfo.specificationCode,
                            userInfo.footType,
                            userInfo.color,
                            userInfo.shoeSize,
                            userInfo.mobileCode
                        )
                        if (userInfo.company == null) {
                            userInfo.company = ""
                        }
                        if (userInfo.featureWords == null) {
                            userInfo.featureWords = ""
                        }
                        if (userInfo.coreWords == null) {
                            userInfo.coreWords = ""
                        }
                        if (userInfo.modelCode == null) {
                            userInfo.modelCode = ""
                        }
                        if (userInfo.specificationCode == null) {
                            userInfo.specificationCode = ""
                        }
                        if (userInfo.footType == null) {
                            userInfo.footType = ""
                        }
                        if (userInfo.color == null) {
                            userInfo.color = ""
                        }
                        if (userInfo.shoeSize == null) {
                            userInfo.shoeSize = ""
                        }
                        if (userInfo.mobileCode == null) {
                            userInfo.mobileCode = ""
                        }
                        getConfigDate(userInfo)
                    }
                } else {
                    val message = toJsonObj["message"] as String
                    ToastUtils().show(this@MainActivity, message)
                }
            }
        })
    }


    private fun getConfigDate(userInfo: UserConfigBean) {
        var company: String = userInfo.company
        Global.companyCode = company
        var featureWords: String = userInfo.featureWords
        Global.shoesCode = featureWords
        var coreWords: String = userInfo.coreWords
        Global.wordCode = coreWords
        var modelCode: String = userInfo.modelCode
        Global.serialCode = modelCode
        var specificationCode: String = userInfo.specificationCode
        Global.specificationCode = specificationCode
        var footType: String = userInfo.footType
        Global.footCode = footType
        var color: String = userInfo.color
        Global.colorCode = color
        var colorConfig = userInfo.mobileCode
        Global.mobileConfig = colorConfig
        var shoeSize: String = userInfo.shoeSize
        Global.sizeCode = shoeSize

        try {
            val dictList = parseDictList(Global.dictConfig)

            dictList.forEach { dictData ->
                println("字典类型: ${dictData.dictName}")

                dictData.items.forEach { item ->
                    if (item.ruleCode.equals(company) && dictData.dictCode.equals("COMPANY")) {
                        Global.companyName = item.ruleName
                        if (item.ruleConfig == null) {
                            Global.companyConfig = ""
                        } else {
                            Global.companyConfig = item.ruleConfig
                        }
                    }
                    if (item.ruleCode.equals(featureWords) && dictData.dictCode.equals("FEATURE_WORDS")) {
                        Global.shoesName = item.ruleName
                        if (item.ruleConfig == null) {
                            Global.shoesConfig = ""
                        } else {
                            Global.shoesConfig = item.ruleConfig
                        }
                        val toJsonObj = JSONObject(Global.shoesConfig)
                        val sizeArrays: JSONArray = toJsonObj.getJSONArray("size")
                        Log.e("MainActivity", "shoesConfig="+sizeArrays)
                        val sizes = sizeList(sizeArrays.toString())
                        sizes.forEach { size ->
                            println("    尺寸: ${size.name} (代码: ${size.code})")
                            if (size.code.equals(shoeSize)) {
                                Global.sizelName = size.name
                            }
                        }
                        val modelArrays: JSONArray = toJsonObj.getJSONArray("model")
                        Log.e("MainActivity", "modelArrays="+modelArrays)
                        val models = sizeList(modelArrays.toString())
                        models.forEach { size ->
                            println("    型号: ${size.name} (代码: ${size.code})")
                            if (size.code.equals(specificationCode)) {
                                Global.specificationName = size.name
                            }
                        }
                        val styleArrays: JSONArray = toJsonObj.getJSONArray("style")
                        Log.e("MainActivity", "modelArrays="+styleArrays)
                        val styles = sizeList(styleArrays.toString())
                        styles.forEach { size ->
                            println("    款式: ${size.name} (代码: ${size.code})")
                            if (size.code.equals(modelCode)) {
                                Global.serialName = size.name
                            }
                        }


                    }
                    if (item.ruleCode.equals(coreWords) && dictData.dictCode.equals("CORE_WORDS")) {
                        Global.wordName = item.ruleName
                        if (item.ruleConfig == null) {
                            Global.wordConfig = ""
                        } else {
                            Global.wordConfig = item.ruleConfig
                        }
                    }
//                    if (item.ruleCode.equals(modelCode) && dictData.dictCode.equals("MODEL_CODE")) {
//                        Global.serialName = item.ruleName
//                        if (item.ruleConfig == null) {
//                            Global.serialConfig = ""
//                        } else {
//                            Global.serialConfig = item.ruleConfig
//                        }
//                    }
//                    if (item.ruleCode.equals(specificationCode) && dictData.dictCode.equals("SPECIFICATION_CODE")) {
//                        Global.specificationName = item.ruleName
//                        Log.e("MainActivity", "specificationName" + Global.specificationName)
//                        if (item.ruleConfig == null) {
//                            Global.specificationConfig = ""
//                        } else {
//                            Global.specificationConfig = item.ruleConfig
//                        }
//                    }
                    if (dictData.dictCode.equals("COLOR") && item.ruleConfig.equals(colorConfig)) {
                        Global.colorlName = item.ruleName
                        if (item.ruleConfig == null) {
                            Global.colorConfig = ""
                        } else {
                            Global.colorConfig = item.ruleConfig
                        }
                    }
                    if (item.ruleCode.equals(footType) && dictData.dictCode.equals("FOOT_TYPE")) {
                        Global.footName = item.ruleName
                        if (item.ruleConfig == null) {
                            Global.footConfig = ""
                        } else {
                            Global.footConfig = item.ruleConfig
                        }
                    }
                    println("  项: ${item.ruleName} (代码: ${item.ruleCode})")

                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        initDate()
    }

    private fun setUserConfig(
        company: String,
        featureWords: String,
        coreWords: String,
        modelCode: String,
        specificationCode: String,
        footType: String,
        color: String,
        shoeSize: String,
        mobileCode: String
    ) {
        val user = UserConfigBean()
        user.company = company
        user.featureWords = featureWords
        user.coreWords = coreWords
        user.modelCode = modelCode
        user.specificationCode = specificationCode
        user.footType = footType
        user.color = color
        user.shoeSize = shoeSize
        user.mobileCode = mobileCode
        val data = Gson().toJson(user)
        OkHttpUtils.postJsonAsync(
            this@MainActivity,
            Api.updateConfig,
            data,
            object : DataCallBack {
                override fun requestFailure(request: Request, e: IOException) {
                }

                @Throws(java.lang.Exception::class)
                override fun requestSuccess(result: String) {
                    val toJsonObj = JSONObject(result)
                    val code = toJsonObj.getInt("code")
                    if (code == 0) {
                    } else {
                        val message = toJsonObj["message"] as String
                        ToastUtils().show(this@MainActivity, message)
                    }
                }
            })
    }

    private fun initDate() {
        companyCode = Global.companyCode
        companyName = Global.companyName
        companyConfig = Global.companyConfig

        wordCode = Global.wordCode
        wordName = Global.wordName
        wordConfig = Global.wordConfig

        shoesCode = Global.shoesCode
        shoesName = Global.shoesName
        shoesConfig = Global.shoesConfig

        serialCode = Global.serialCode
        serialName = Global.serialName
        serialConfig = Global.serialConfig

        colorCode = Global.colorCode
        colorlName = Global.colorlName
        colorConfig = Global.colorConfig

        sizeCode = Global.sizeCode
        sizelName = Global.sizelName
        sizeConfig = Global.sizeConfig

        specificationCode = Global.specificationCode
        specificationName = Global.specificationName
        specificationConfig = Global.specificationConfig

    }

    private fun showCailbDownIc(rxDialogCali: RxDialogcalibrateSureCancel) {
        runOnUiThread {
            rxDialogCali.ivDialogShoesSize.visibility = View.VISIBLE
            rxDialogCali.ivDialogShoesType.visibility = View.VISIBLE
            rxDialogCali.dialogLlShoesType.isEnabled = true
            rxDialogCali.dialogLlShoesSize.isEnabled = true
        }

    }
    private fun showDownIc(rxDialogSureCancel: RxDialogWriteSureCancel) {
        runOnUiThread { rxDialogSureCancel.ivDialogTvWriteCompany.visibility = View.VISIBLE
            rxDialogSureCancel.ivDialogTvWriteCodeWord.visibility = View.VISIBLE
            rxDialogSureCancel.ivDialogTvWriteShoesType.visibility = View.VISIBLE
            rxDialogSureCancel.ivDialogTvWriteSerialType.visibility = View.VISIBLE
            rxDialogSureCancel.ivDialogTvWriteShoesColor.visibility = View.VISIBLE
            rxDialogSureCancel.ivDialogTvWriteShoesSize.visibility = View.VISIBLE
            rxDialogSureCancel.ivDialogTvWriteSpecification.visibility = View.VISIBLE
            rxDialogSureCancel.dialogTvWriteFootTypeLeft.visibility = View.VISIBLE
            rxDialogSureCancel.dialogTvWriteFootTypeRight.visibility = View.VISIBLE
            if (Global.footName.equals("左脚")) {
                rxDialogSureCancel.dialogTvWriteFootTypeLeft.setBackgroundResource(R.drawable.bg_orange_btn)
                rxDialogSureCancel.dialogTvWriteFootTypeLeft.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.white))
                rxDialogSureCancel.dialogTvWriteFootTypeRight.setBackgroundResource(R.drawable.bg_black_frame_btn)
                rxDialogSureCancel.dialogTvWriteFootTypeRight.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.black))
            } else if (Global.footName.equals("右脚")) {
                rxDialogSureCancel.dialogTvWriteFootTypeRight.setBackgroundResource(R.drawable.bg_orange_btn)
                rxDialogSureCancel.dialogTvWriteFootTypeRight.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.white))
                rxDialogSureCancel.dialogTvWriteFootTypeLeft.setBackgroundResource(R.drawable.bg_black_frame_btn)
                rxDialogSureCancel.dialogTvWriteFootTypeLeft.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.black))
            } else {
                rxDialogSureCancel.dialogTvWriteFootTypeRight.setBackgroundResource(R.drawable.bg_black_frame_btn)
                rxDialogSureCancel.dialogTvWriteFootTypeRight.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.black))
                rxDialogSureCancel.dialogTvWriteFootTypeLeft.setBackgroundResource(R.drawable.bg_black_frame_btn)
                rxDialogSureCancel.dialogTvWriteFootTypeLeft.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.black))
            }

            rxDialogSureCancel.dialogLlWriteCompany.isEnabled = true
            rxDialogSureCancel.dialogLlWriteCodeWord.isEnabled = true
            rxDialogSureCancel.dialogLlWriteShoesType.isEnabled = true
            rxDialogSureCancel.dialogLlWriteSerialType.isEnabled = true
            rxDialogSureCancel.dialogLlWriteShoesColor.isEnabled = true
            rxDialogSureCancel.dialogLlWriteShoesSize.isEnabled = true
            rxDialogSureCancel.dialogLlWriteSpecification.isEnabled = true }
    }
    private fun dissCalibDownIc(rxDialogCali: RxDialogcalibrateSureCancel) {
        runOnUiThread {
            rxDialogCali.ivDialogShoesSize.visibility = View.GONE
            rxDialogCali.ivDialogShoesType.visibility = View.GONE
            rxDialogCali.dialogLlShoesType.isEnabled = false
            rxDialogCali.dialogLlShoesSize.isEnabled = false
        }

    }

    private fun dissDownIc(rxDialogSureCancel: RxDialogWriteSureCancel) {
        runOnUiThread { rxDialogSureCancel.ivDialogTvWriteCompany.visibility = View.GONE
            rxDialogSureCancel.ivDialogTvWriteCodeWord.visibility = View.GONE
            rxDialogSureCancel.ivDialogTvWriteShoesType.visibility = View.GONE
            rxDialogSureCancel.ivDialogTvWriteSerialType.visibility = View.GONE
            rxDialogSureCancel.ivDialogTvWriteShoesColor.visibility = View.GONE
            rxDialogSureCancel.ivDialogTvWriteShoesSize.visibility = View.GONE
            rxDialogSureCancel.ivDialogTvWriteSpecification.visibility = View.GONE
            rxDialogSureCancel.dialogTvWriteFootTypeLeft.visibility = View.GONE
            rxDialogSureCancel.dialogTvWriteFootTypeRight.visibility = View.GONE

            rxDialogSureCancel.dialogLlWriteCompany.isEnabled = false
            rxDialogSureCancel.dialogLlWriteCodeWord.isEnabled = false
            rxDialogSureCancel.dialogLlWriteShoesType.isEnabled = false
            rxDialogSureCancel.dialogLlWriteSerialType.isEnabled = false
            rxDialogSureCancel.dialogLlWriteShoesColor.isEnabled = false
            rxDialogSureCancel.dialogLlWriteShoesSize.isEnabled = false
            rxDialogSureCancel.dialogLlWriteSpecification.isEnabled = false }

    }
    private fun setDialogDate(rxDialogSureCancel: RxDialogWriteSureCancel) {
        runOnUiThread {
            rxDialogSureCancel.dialogTvWriteCompanyValue.text = Global.companyName
            rxDialogSureCancel.dialogTvWriteCodeWordValue.text = Global.wordName
            rxDialogSureCancel.dialogTvWriteShoesTypeValue.text = Global.shoesName
            rxDialogSureCancel.dialogTvWriteSerialTypeValue.text = Global.serialName
            rxDialogSureCancel.dialogTvWriteShoesColorValue.text = Global.colorlName
            rxDialogSureCancel.dialogTvWriteShoesSizeValue.text = Global.sizelName
            rxDialogSureCancel.dialogTvWriteSpecificationValue.text = Global.specificationName
            rxDialogSureCancel.dialogTvWriteFootTypeValue.text = Global.footName

        }
    }
    private fun setCalibDialogDate(rxDialogSureCancel: RxDialogcalibrateSureCancel) {
        runOnUiThread {
            rxDialogSureCancel.dialogTvShoesTypeValue.text = Global.shoesName
            rxDialogSureCancel.dialogTvShoesSizeValue.text = Global.sizelName
        }
    }

    // 常量定义
    private val TAG = "OptimizedLocation"
    private val LOCATION_PERMISSION_REQUEST_CODE = 1001
    private val LOCATION_TIMEOUT = 30000L // 30秒定位超时
    private val MIN_VALID_LOCATION_AGE = 5 * 60 * 1000L // 5分钟内的位置视为有效
    private val MAX_ACCEPTABLE_ACCURACY = 1000f // 最大可接受的定位精度（米）

    // 定位相关变量
    private lateinit var locationManager: LocationManager
    private var isLocationReceived = false
    private var locationTimeoutJob: kotlinx.coroutines.Job? = null
    private var isLocationRequestActive = false

    // 全局位置存储（根据实际需求修改）
    object GlobalLocation {
        var lat: Double = 0.0
        var lng: Double = 0.0
        var accuracy: Float = 0f
        var updateTime: Long = 0
    }

    // 定位错误类型
    private enum class LocationError {
        PERMISSION_DENIED,
        SERVICE_DISABLED,
        PROVIDER_UNAVAILABLE,
        TIMEOUT,
        NETWORK_ERROR,
        UNKNOWN_ERROR
    }

    /**
     * 启动完整的定位流程
     */
    private fun startLocationProcess() {
        // 重置状态
        isLocationReceived = false
        isLocationRequestActive = true

        // 检查权限
        if (checkLocationPermissions()) {
            // 权限已获取，检查定位服务
            if (isLocationServiceEnabled()) {
                // 检查网络（针对网络定位）
                if (isNetworkProviderEnabled() && !isNetworkAvailable()) {
                    handleLocationError(LocationError.NETWORK_ERROR)
                    return
                }

                // 启动定位
                startLocationUpdates()
            } else {
                handleLocationError(LocationError.SERVICE_DISABLED)
            }
        }
    }
    /**
     * 检查定位权限
     */
    private fun checkLocationPermissions(): Boolean {
        // 如果已经有活跃的位置请求，直接返回false
        if (isLocationRequestActive) {
            return false
        }
        // 根据Android版本确定所需权限
        val requiredPermissions = mutableListOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )

        // Android 10及以上需要后台定位权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            requiredPermissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
        }

        // 检查未授予的权限
        val permissionsToRequest = requiredPermissions.filter {
            ContextCompat.checkSelfPermission(this@MainActivity, it) != PackageManager.PERMISSION_GRANTED
        }

        return if (permissionsToRequest.isNotEmpty()) {
            // 设置状态为有活跃的位置请求
            isLocationRequestActive = true
            ActivityCompat.requestPermissions(
                this@MainActivity,
                permissionsToRequest.toTypedArray(),
                LOCATION_PERMISSION_REQUEST_CODE
            )
            false
        } else {
            true
        }
    }

    /**
     * 检查定位服务是否开启
     */
    private fun isLocationServiceEnabled(): Boolean {
        return try {
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ||
                    locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        } catch (e: Exception) {
            Log.e(TAG, "检查定位服务失败", e)
            false
        }
    }

    /**
     * 检查网络定位是否开启
     */
    private fun isNetworkProviderEnabled(): Boolean {
        return try {
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        } catch (e: Exception) {
            Log.e(TAG, "检查网络定位失败", e)
            false
        }
    }

    /**
     * 检查GPS定位是否开启
     */
    private fun isGpsProviderEnabled(): Boolean {
        return try {
            locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        } catch (e: Exception) {
            Log.e(TAG, "检查GPS定位失败", e)
            false
        }
    }

    /**
     * 检查网络是否可用
     */
    @SuppressLint("MissingPermission")
    private fun isNetworkAvailable(): Boolean {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork ?: return false
            val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo ?: return false
            @Suppress("DEPRECATION")
            networkInfo.isConnected
        }
    }

    /**
     * 启动定位更新
     */
    @SuppressLint("MissingPermission")
    private fun startLocationUpdates() {
        try {
            // 先尝试获取最后已知位置
            val lastKnownLocation = getBestLastKnownLocation()
            lastKnownLocation?.let {
                if (isLocationValid(it)) {
                    handleValidLocation(it, "最后已知位置")
                    isLocationReceived = true
                }
            }

            // 启动定位超时任务
            locationTimeoutJob = CoroutineScope(Dispatchers.Main).launch {
                delay(LOCATION_TIMEOUT)
                if (!isLocationReceived && isLocationRequestActive) {
                    handleLocationError(LocationError.TIMEOUT)
                    stopLocationUpdates()
                }
            }

            // 启动网络定位（如果可用）
            if (isNetworkProviderEnabled()) {
                locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    5000,   // 5秒间隔
                    5f,     // 5米距离变化
                    networkLocationListener,
                    Looper.getMainLooper()
                )
                Log.d(TAG, "已启动网络定位")
            }

            // 启动GPS定位（如果可用）
            if (isGpsProviderEnabled()) {
                locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    5000,   // 5秒间隔
                    5f,     // 5米距离变化
                    gpsLocationListener,
                    Looper.getMainLooper()
                )
                Log.d(TAG, "已启动GPS定位")
            }

        } catch (e: SecurityException) {
            Log.e(TAG, "定位权限异常", e)
            handleLocationError(LocationError.PERMISSION_DENIED)
        } catch (e: Exception) {
            Log.e(TAG, "启动定位失败", e)
            handleLocationError(LocationError.UNKNOWN_ERROR)
        }
    }

    /**
     * 获取最佳的最后已知位置
     */
    @SuppressLint("MissingPermission")
    private fun getBestLastKnownLocation(): Location? {
        return try {
            val locations = mutableListOf<Location?>()

            // 获取网络定位的最后已知位置
            if (isNetworkProviderEnabled()) {
                locations.add(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER))
            }

            // 获取GPS定位的最后已知位置
            if (isGpsProviderEnabled()) {
                locations.add(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER))
            }

            // 筛选出有效的位置，并选择最新的
            locations
                .filterNotNull()
                .filter { isLocationValid(it) }
                .maxByOrNull { it.time }
        } catch (e: Exception) {
            Log.e(TAG, "获取最后已知位置失败", e)
            null
        }
    }

    /**
     * 验证位置是否有效
     */
    private fun isLocationValid(location: Location): Boolean {
        // 检查位置时间是否在有效期内
        val isRecent = System.currentTimeMillis() - location.time < MIN_VALID_LOCATION_AGE
        // 检查位置精度
        val isAccurateEnough = location.accuracy <= MAX_ACCEPTABLE_ACCURACY
        // 检查经纬度是否有效
        val hasValidCoordinates = location.latitude != 0.0 && location.longitude != 0.0

        return isRecent && isAccurateEnough && hasValidCoordinates
    }

    /**
     * 处理有效的位置信息
     */
    private fun handleValidLocation(location: Location, source: String) {
        // 更新全局位置
        GlobalLocation.lat = location.latitude
        GlobalLocation.lng = location.longitude
        GlobalLocation.accuracy = location.accuracy
        GlobalLocation.updateTime = System.currentTimeMillis()

        // 输出日志
        val locationInfo = String.format(
            Locale.getDefault(),
            "%s:\n纬度: %.6f\n经度: %.6f\n精度: %.1f米\n时间: %s",
            source,
            location.latitude,
            location.longitude,
            location.accuracy,
            Date(location.time).toString()
        )
        Log.d(TAG, locationInfo)
//        Toast.makeText(this, locationInfo, Toast.LENGTH_LONG).show()

        // 标记已收到位置，取消超时任务
        isLocationReceived = true
        locationTimeoutJob?.cancel()

        // 这里可以添加后续业务逻辑，如上传位置等
        // processLocation(location)
        Global.lat = location.latitude
        Global.lng = location.longitude
//        ToastUtils().show(this@MainActivity, locationInfo)
    }

    /**
     * 停止定位更新
     */
    private fun stopLocationUpdates() {
        try {
            locationManager.removeUpdates(networkLocationListener)
            locationManager.removeUpdates(gpsLocationListener)
            locationTimeoutJob?.cancel()
            isLocationRequestActive = false
            Log.d(TAG, "已停止定位更新")
        } catch (e: Exception) {
            Log.e(TAG, "停止定位更新失败", e)
        }
    }

    /**
     * 处理定位错误
     */
    private fun handleLocationError(error: LocationError) {
        val errorMsg = when (error) {
            LocationError.PERMISSION_DENIED -> "定位权限被拒绝，请在设置中开启"
            LocationError.SERVICE_DISABLED -> "请开启定位服务（设置->位置信息）"
            LocationError.PROVIDER_UNAVAILABLE -> "当前环境无法获取位置，请稍后重试"
            LocationError.TIMEOUT -> "定位超时，请移动到开阔地带重试"
            LocationError.NETWORK_ERROR -> "网络异常，无法使用网络定位"
            LocationError.UNKNOWN_ERROR -> "定位失败，请稍后重试"
        }

        Log.e(TAG, "定位错误: $errorMsg")
//        Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()
        ToastUtils().show(this@MainActivity, errorMsg)

        // 根据错误类型引导用户
        when (error) {
            LocationError.PERMISSION_DENIED -> navigateToAppSettings()
            LocationError.SERVICE_DISABLED -> navigateToLocationSettings()
            else -> {}
        }
    }

    /**
     * 导航到应用设置页面
     */
    private fun navigateToAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = android.net.Uri.fromParts("package", packageName, null)
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        startActivity(intent)
    }

    /**
     * 导航到系统定位设置页面
     */
    private fun navigateToLocationSettings() {
        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        startActivity(intent)
    }

    /**
     * 网络定位监听器
     */
    private val networkLocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            if (isLocationValid(location)) {
                handleValidLocation(location, "网络定位")
            } else {
                Log.w(TAG, "网络定位位置无效，忽略")
            }
        }

        override fun onProviderDisabled(provider: String) {
            Log.w(TAG, "网络定位已关闭")
            if (!isLocationReceived && isGpsProviderEnabled().not()) {
                handleLocationError(LocationError.PROVIDER_UNAVAILABLE)
            }
        }

        override fun onProviderEnabled(provider: String) {
            Log.d(TAG, "网络定位已开启")
            if (!isLocationReceived) {
                startLocationUpdates()
            }
        }

        @Deprecated("Deprecated in Java")
        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            Log.d(TAG, "网络定位状态变化: $status")
        }
    }

    /**
     * GPS定位监听器
     */
    private val gpsLocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            if (isLocationValid(location)) {
                handleValidLocation(location, "GPS定位")
            } else {
                Log.w(TAG, "GPS定位位置无效，忽略")
            }
        }

        override fun onProviderDisabled(provider: String) {
            Log.w(TAG, "GPS定位已关闭")
            if (!isLocationReceived && isNetworkProviderEnabled().not()) {
                handleLocationError(LocationError.PROVIDER_UNAVAILABLE)
            }
        }

        override fun onProviderEnabled(provider: String) {
            Log.d(TAG, "GPS定位已开启")
            if (!isLocationReceived) {
                startLocationUpdates()
            }
        }

        @Deprecated("Deprecated in Java")
        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            Log.d(TAG, "GPS定位状态变化: $status")
        }
    }

    /**
     * 权限请求结果处理
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }

            if (allGranted) {
                // 权限已授予，继续定位流程
                if (isLocationServiceEnabled()) {
                    // 直接启动定位，而不是调用 startLocationProcess()
                    startLocationUpdates()
                } else {
                    handleLocationError(LocationError.SERVICE_DISABLED)
                }
            } else {
                // 检查是否勾选了"不再询问"
                val shouldShowRationale = permissions.any {
                    ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity, it)
                }

                if (!shouldShowRationale) {
                    // 用户勾选了"不再询问"，引导到设置页面
                    handleLocationError(LocationError.PERMISSION_DENIED)
                } else {
                    // 用户拒绝但未勾选"不再询问"
                    ToastUtils().show(this@MainActivity, "需要定位权限才能获取位置信息")
//                    Toast.makeText(this, "需要定位权限才能获取位置信息", Toast.LENGTH_SHORT).show()
                }
                isLocationRequestActive = false
            }
        }
    }


    private fun selectCalibDate(rxDialogCalib: RxDialogcalibrateSureCancel, view: TextView, arrays: List<DictItem>, tag: Int) {
        // 测量文本最大宽度
        var maxWidth = 0f
        var item: String = ""
        // 测量文本最大宽度
        val paint = Paint()
        for (i in 0 until arrays.size) {
            item = arrays.get(i).ruleName
            val width = paint.measureText(item)
            if (width > maxWidth) {
                maxWidth = width
            }
        }


        val popupSheet: PopupSheet
        val showArrayList = arrays//Arrays.asList(/* ...a = */ *arrays)
        popupSheet =
            PopupSheet(this@MainActivity, view, showArrayList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@MainActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", showArrayList[position].ruleName)
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    view.text = showArrayList[position].ruleName
                    if (showArrayList[position].ruleConfig == null) {
                        setCalibSerValue(rxDialogCalib, tag, showArrayList[position].ruleCode, showArrayList[position].ruleName, "")
                    } else {
                        setCalibSerValue(
                            rxDialogCalib,
                            tag,
                            showArrayList[position].ruleCode,
                            showArrayList[position].ruleName,
                            showArrayList[position].ruleConfig
                        )
                    }
//                    ToastUtils().show(this@MainBoardActivity, "你选择了"+showArrayList[position])
//                    tvShoesSize.text = MessageFormat.format("{0}", "鞋子尺码：$shoesSize")
                }
            }, DimensUtil.dp2px(this@MainActivity, maxWidth+80F))
        popupSheet.show()
    }


    private fun setCalibSerValue(rxDialogCalib: RxDialogcalibrateSureCancel, p0: Int, code: String, name: String, config: String) {
        when (p0) {
            2 -> {
                if (!shoesCode.equals(name)) {
//                    sizeCode = ""
                    sizelName = ""
//                    sizeConfig = ""
//                    Global.sizelName = ""
//                    Global.sizeCode = ""
//                    Global.sizeConfig = ""
                }
//                Global.shoesCode = shoesCode
//                Global.shoesName = shoesName
//                Global.shoesConfig = shoesConfig
                shoesCode = code
                shoesName = name
                shoesConfig = config
                runOnUiThread {
                    rxDialogCalib.dialogTvShoesTypeValue.text = shoesName
                    rxDialogCalib.dialogTvShoesSizeValue.text = sizelName
                }
            }
            5 -> {
                sizeCode = code
                sizelName = name
//                sizeConfig = config
//                Global.sizeCode = sizeCode
//                Global.sizelName = sizelName
//                Global.sizeConfig = sizeConfig
                runOnUiThread {
                    rxDialogCalib.dialogTvShoesSizeValue.text = sizelName
                }
            }
        }

    }

    private fun selectCalibSizeDate(rxDialogCalib: RxDialogcalibrateSureCancel, view: TextView, arrays: List<SizeConfig>, tag: Int) {
        // 测量文本最大宽度
        var maxWidth = 0f
        var item: String = ""
        // 测量文本最大宽度
        val paint = Paint()
        for (i in 0 until arrays.size) {
            item = arrays.get(i).name
            val width = paint.measureText(item)
            if (width > maxWidth) {
                maxWidth = width
            }
        }
        val popupSheet: PopupSheet
        val showArrayList = arrays//Arrays.asList(/* ...a = */ *arrays)
        popupSheet =
            PopupSheet(this@MainActivity, view, showArrayList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@MainActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", showArrayList[position].name)
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    view.text = showArrayList[position].name
                    setCalibSerValue(rxDialogCalib, tag, showArrayList[position].code, showArrayList[position].name, "")
//                    ToastUtils().show(this@MainBoardActivity, "你选择了"+showArrayList[position])
//                    tvShoesSize.text = MessageFormat.format("{0}", "鞋子尺码：$shoesSize")
                }
            }, DimensUtil.dp2px(this@MainActivity, maxWidth+80F))
        popupSheet.show()
    }

    private fun getCalibConfig(rxDialogSureCancel: RxDialogWriteSureCancel, calibShoesTypeCode: String, calibShoesSizeCode: String) {//rxDialogCalib: RxDialogcalibrateSureCancel,
        OkHttpUtils.getAsyncToken(this@MainActivity, Api.calibrateConfig+"?type="+calibShoesTypeCode+"&size="+calibShoesSizeCode, true, object : DataCallBack {
            override fun requestFailure(request: Request, e: IOException) {
            }

            @SuppressLint("SetTextI18n")
            @Throws(Exception::class)
            override fun requestSuccess(result: String) {
                val toJsonObj = JSONObject(result)
                Log.e("getCalibConfig", "返回$toJsonObj")
                val code = toJsonObj.getInt("code")
                if (code == 0) {
//                    Global.shoesConfig = shoesConfig
//                    Global.shoesCode = shoesCode
//                    Global.shoesName = shoesName
//                    Global.sizeConfig = sizeConfig
//                    Global.sizeCode = sizeCode
//                    Global.sizelName = sizelName
                    if (result.contains("data")) {
                        val data = toJsonObj.optJSONObject("data")
                        if (data == null) {
                            ToastUtils().show(this@MainActivity, "选择的该产品类型尺码，没有定标范围值")
                        } else {
                            val jsonData = data.getString("items")
                            Global.CalibConfig = jsonData.toString()
                            goIntentCalib()
//                            val intent = Intent(this@MainActivity, CalibrateActivity::class.java)
//                            startActivity(intent)
                            rxDialogSureCancel.cancel()
                        }

                    }
                } else {
                    val message = toJsonObj["message"] as String
                    ToastUtils().show(this@MainActivity, message)
                }
            }
        })

    }

    private fun showDialog(tag: String) {
        val rxDialogSureCancel: RxDialogWriteSureCancel =
            RxDialogWriteSureCancel(this@MainActivity)
        setDialogDate(rxDialogSureCancel)
        if (Global.companyName.equals("") || Global.wordName.equals("") || Global.shoesName.equals(
                ""
            ) ||
            Global.serialName.equals("") || Global.colorlName.equals("") || Global.sizelName.equals(
                ""
            ) ||
            Global.specificationName.equals("") || Global.footName.equals("")
        ) {
//                    showDownIc(rxDialogSureCancel)
            rxDialogSureCancel.cancelView.text = "完善"
        }

//                rxDialogSureCancel.dialogLlWriteCompany.isEnabled = false
//                rxDialogSureCancel.dialogLlWriteCodeWord.isEnabled = false
//                rxDialogSureCancel.dialogLlWriteShoesType.isEnabled = false
//                rxDialogSureCancel.dialogLlWriteSerialType.isEnabled = false
//                rxDialogSureCancel.dialogLlWriteShoesColor.isEnabled = false
//                rxDialogSureCancel.dialogLlWriteShoesSize.isEnabled = false
//                rxDialogSureCancel.dialogLlWriteSpecification.isEnabled = false

        rxDialogSureCancel.setdialogLlWriteCompanyListener {
            dictLists = getItems("COMPANY")
            selectDate(rxDialogSureCancel, rxDialogSureCancel.dialogTvWriteCompanyValue, dictLists, 0)
        }
        rxDialogSureCancel.setdialogLlWriteCodeWordListener {
            dictLists = getItems("CORE_WORDS")
            selectDate(rxDialogSureCancel, rxDialogSureCancel.dialogTvWriteCodeWordValue, dictLists, 1)
        }
        rxDialogSureCancel.setdialogTvWriteShoesTypeValueListener(View.OnClickListener {
            dictLists = getItems("FEATURE_WORDS")
            selectDate(rxDialogSureCancel, rxDialogSureCancel.dialogTvWriteShoesTypeValue, dictLists, 2)
        })
        rxDialogSureCancel.setdialogTvWriteSerialTypeValueListener(View.OnClickListener {
            if (Global.shoesConfig.equals("")) {
                ToastUtils().show(this@MainActivity, "请先选择产品类型")
                return@OnClickListener
            }
            val toJsonObj = JSONObject(Global.shoesConfig)
            val styleArrays: JSONArray = toJsonObj.getJSONArray("style")
            Log.e("MainActivity", "styleArrays="+styleArrays)
            val styles = sizeList(styleArrays.toString())
            selectSizeDate(rxDialogSureCancel, rxDialogSureCancel.dialogTvWriteSerialTypeValue, styles, 3)


//            dictLists = getItems("MODEL_CODE")
//            val arrays: Array<String> = resources.getStringArray(R.array.shoe_serial_type)
//            selectDate(rxDialogSureCancel,rxDialogSureCancel.dialogTvWriteSerialTypeValue, dictLists, 3)
        })
        rxDialogSureCancel.setdialogTvWriteShoesColorValueListener(View.OnClickListener {
            dictLists = getItems("COLOR")
//                    val arrays: Array<String> = resources.getStringArray(R.array.shoes_color)
            selectDate(rxDialogSureCancel,rxDialogSureCancel.dialogTvWriteShoesColorValue, dictLists, 4)
        })
        rxDialogSureCancel.setdialogLlWriteSpecificationListener(View.OnClickListener {
            if (Global.shoesConfig.equals("")) {
                ToastUtils().show(this@MainActivity, "请先选择产品类型")
                return@OnClickListener
            }
            val toJsonObj = JSONObject(Global.shoesConfig)
//            Log.e("MainActivity", "modelArrays="+toJsonObj)
            val modelArrays: JSONArray = toJsonObj.getJSONArray("model")
            Log.e("MainActivity", "modelArrays="+modelArrays)
            val models = sizeList(modelArrays.toString())
            selectSizeDate(rxDialogSureCancel, rxDialogSureCancel.dialogTvWriteSpecificationValue, models, 6)

//            dictLists = getItems("SPECIFICATION_CODE")
////                    val arrays: Array<String> = resources.getStringArray(R.array.shoes_color)
//            selectDate(rxDialogSureCancel,rxDialogSureCancel.dialogTvWriteSpecificationValue, dictLists, 6)
        })
        Global.footName = "左脚"
        Global.footCode = "Z"
        Global.footConfig = ""
//        rxDialogSureCancel.setDialogTvWriteFootTypeLeftListener(View.OnClickListener {
//            Global.footName = "左脚"
//            Global.footCode = "Z"
//            Global.footConfig = ""
//            rxDialogSureCancel.dialogTvWriteFootTypeValue.text = Global.footName
//            rxDialogSureCancel.dialogTvWriteFootTypeLeft.setBackgroundResource(R.drawable.bg_orange_btn)
//            rxDialogSureCancel.dialogTvWriteFootTypeLeft.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.white))
//            rxDialogSureCancel.dialogTvWriteFootTypeRight.setBackgroundResource(R.drawable.bg_black_frame_btn)
//            rxDialogSureCancel.dialogTvWriteFootTypeRight.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.black))
//        })
//        rxDialogSureCancel.setDialogTvWriteFootTypeRightListener(View.OnClickListener {
//            Global.footName = "右脚"
//            Global.footCode = "Y"
//            Global.footConfig = ""
//            rxDialogSureCancel.dialogTvWriteFootTypeValue.text = Global.footName
//            rxDialogSureCancel.dialogTvWriteFootTypeRight.setBackgroundResource(R.drawable.bg_orange_btn)
//            rxDialogSureCancel.dialogTvWriteFootTypeRight.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.white))
//            rxDialogSureCancel.dialogTvWriteFootTypeLeft.setBackgroundResource(R.drawable.bg_black_frame_btn)
//            rxDialogSureCancel.dialogTvWriteFootTypeLeft.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.black))
//        })
        rxDialogSureCancel.setdialogTvWriteShoesSizeValueListener(View.OnClickListener {
            if (Global.shoesConfig.equals("")) {
                ToastUtils().show(this@MainActivity, "请先选择产品类型")
                return@OnClickListener
            }
            val toJsonObj = JSONObject(Global.shoesConfig)
            val sizeArrays: JSONArray = toJsonObj.getJSONArray("size")
            Log.e("MainActivity", "shoesConfig="+sizeArrays)
            val sizes = sizeList(sizeArrays.toString())
            selectSizeDate(rxDialogSureCancel, rxDialogSureCancel.dialogTvWriteShoesSizeValue, sizes, 5)

        })
        rxDialogSureCancel.setCancelListener {
            if (rxDialogSureCancel.cancelView.text.equals("修改") || rxDialogSureCancel.cancelView.text.equals("完善")) {
                showDownIc(rxDialogSureCancel)
                rxDialogSureCancel.cancelView.text = "取消"
            } else if (rxDialogSureCancel.cancelView.text.equals("取消")) {
                dissDownIc(rxDialogSureCancel)
                rxDialogSureCancel.cancelView.text = "修改"
//                        rxDialogSureCancel.dismiss()
            }
        }
        rxDialogSureCancel.setSureListener {
            if (Global.companyName.equals("")) {
                ToastUtils().show(this@MainActivity, "请选择公司")
                return@setSureListener
            }
            if (Global.wordName.equals("")) {
                ToastUtils().show(this@MainActivity, "请选择核心词")
                return@setSureListener
            }
            if (Global.shoesName.equals("")) {
                ToastUtils().show(this@MainActivity, "请选择产品")
                return@setSureListener
            }
            if (Global.serialName.equals("")) {
                ToastUtils().show(this@MainActivity, "请选择款式")
                return@setSureListener
            }
            if (Global.colorlName.equals("")) {
                ToastUtils().show(this@MainActivity, "请选择颜色")
                return@setSureListener
            }
            if (Global.sizelName.equals("")) {
                ToastUtils().show(this@MainActivity, "请选择尺码")
                return@setSureListener
            }
            if (Global.specificationName.equals("")) {
                ToastUtils().show(this@MainActivity, "请选择规格")
                return@setSureListener
            }
//            if (Global.footName.equals("")) {
//                ToastUtils().show(this@MainActivity, "请选择左右脚")
//                return@setSureListener
//            }
            if (tag.equals("0")) {
                intentCalibActivity(rxDialogSureCancel)
            } else if (tag.equals("1")) {
                intentWriteActivity()
                rxDialogSureCancel.dismiss()
            }

        }
        dissDownIc(rxDialogSureCancel)
        rxDialogSureCancel.show()
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
            text = "Hello $name!",
            modifier = modifier
    )
}



@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ERASLineOfProductionTheme {
        Greeting("Android")
    }
}